package com.net.xpay.core.helper;

import com.net.xpay.core.utils.UuidUtil;
import org.aspectj.util.FileUtil;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDateTime;

@Component
public class QrCodeHelper {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private UploadHelper uploadHelper;


    public String genThenUpload(String content) throws IOException {
        BufferedImage image = new SimpleQrcodeGenerator().generate(content).getImage();
        InputStream in =  bufferedImageToInputStream(image);

        LocalDateTime expired = LocalDateTime.now().plusYears(500L);
        return uploadHelper.upload(UuidUtil.uuid() + ".png", in, expired);
    }

    /**
     * 将BufferedImage转换为InputStream
     */
    private InputStream bufferedImageToInputStream(BufferedImage image) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        return new ByteArrayInputStream(os.toByteArray());
    }
}
